<?php 
class GacSachModel extends CI_Model {
	
	public function get_categories() {
		$rows = $this->db->query("SELECT id, name, tag FROM category");
		$data = array();
		foreach($rows->result() as $row) {
			array_push($data, $row);
		}
		return $data;
	}
	
	function test() {
		$this->db->select('id, name');
		$query = $this->db->get('story');
		var_dump($query);
	}
	
	function get_top_stories($page, $page_num) {
		$this->db->select('COUNT(id) as total_rows');
		$this->db->where('is_active', 1);
		$query = $this->db->get('story');
		$total_rows = 0;
		foreach($query->result() as $row) {
			$total_rows = $row->total_rows;
		}
		$total_pages = floor($total_rows / $page_num);
		$start_row = ($page - 1) * $page_num;
		$this->db->select('id, name, author, thumbnail, description, chapter_num, view_count, tag');
		$this->db->where('is_active', 1);
		$this->db->where('chapter_num >', 0);
		$this->db->order_by('view_count', 'desc');
		$query = $this->db->get('story', $page_num, $start_row);
		$data = array();
		foreach($query->result() as $row) {
			$data[] = $row;
		}
		$std = new stdClass();
		$std->num_pages = min($total_pages, 10);
		$std->page = $page;
		$std->data = $data;
		return $std;
	}
	
	function get_stories($tag, $page, $page_num=15, $order_coloumn_name='name', $order_value='asc') {
		$this->db->select('COUNT(id) as total_rows');
		$this->db->where('is_active', 1);
		$this->db->like('tag', $tag);
		$query = $this->db->get('story');
		$total_rows = 0;
		foreach($query->result() as $row) {
			$total_rows = $row->total_rows;
		}
		$total_pages = floor($total_rows / $page_num);
		$start_row = ($page - 1) * $page_num;
		$this->db->select('id, name, author, thumbnail, description, chapter_num, view_count, tag');
		$this->db->where('is_active', 1);
		$this->db->where('chapter_num >', 0);
		$this->db->like('tag', $tag);
		
		if ($order_coloumn_name != 'name' && $order_coloumn_name != 'view_count') {
			$order_coloumn_name = 'name';
		}
		
		$this->db->order_by($order_coloumn_name, $order_value);
		$query = $this->db->get('story', $page_num, $start_row);		
		$data = array();
		foreach($query->result() as $row) {
			$data[] = $row;
		}
		$std = new stdClass();
		$std->num_pages = $total_pages;
		$std->page = $page;
		$std->data = $data;
		return $std;
	}
	
	function get_story($id) {
		$this->db->select('id, name, author, thumbnail, description, chapter_num, view_count, tag');
		$this->db->where('id', $id);
		$query = $this->db->get('story');
		$data = null;
		foreach($query->result() as $row) {
			$data = $row;
		}
		return $data;
	}
}
?>